# UpgradeScreen.gd
extends CanvasLayer

@onready var option_container = $Panel/MarginContainer/VBoxContainer

# You need to create a separate scene for the option button, e.g., UpgradeOptionButton.tscn
# It should contain a Button and Labels for Title, Description.
# The script for UpgradeOptionButton should store the upgrade resource and emit a signal on press.
@export var option_button_scene: PackedScene # = preload("res://scenes/ui/UpgradeOptionButton.tscn")

var upgrade_options: Array[Resource] = []

func _ready():
	hide() # Start hidden
	SignalBus.show_upgrade_screen.connect(show_options)
	print("UpgradeScreen Ready")


func show_options(options: Array[Resource]):
	if not options or options.is_empty():
		printerr("UpgradeScreen received no options!")
		# Maybe resume game automatically?
		if GameManager.is_paused: GameManager.resume_game()
		return

	upgrade_options = options

	# Clear previous options
	for child in option_container.get_children():
		child.queue_free()

	# Instantiate and setup new option buttons
	for i in range(options.size()):
		var option_res = options[i]
		if not option_res:
			printerr("Invalid upgrade resource at index ", i)
			continue

		if not option_button_scene:
			printerr("UpgradeOptionButton scene not set in UpgradeScreen!")
			continue

		var option_button_instance = option_button_scene.instantiate()
		option_container.add_child(option_button_instance)

		# Assuming UpgradeOptionButton.gd has a function `set_upgrade_data`
		if option_button_instance.has_method("set_upgrade_data"):
			option_button_instance.set_upgrade_data(option_res)
			# Connect the button's signal to our handler
			if not option_button_instance.is_connected("upgrade_selected", Callable(self, "_on_upgrade_selected")):
				option_button_instance.connect("upgrade_selected", Callable(self, "_on_upgrade_selected"))
		else:
			printerr("UpgradeOptionButton scene instance is missing set_upgrade_data method.")


	show()


func _on_upgrade_selected(chosen_upgrade: Resource):
	print("Upgrade chosen in UI: ", chosen_upgrade.resource_path if chosen_upgrade else "None")
	hide()
	# Let UpgradeManager handle applying the upgrade and resuming the game
	UpgradeManager.apply_upgrade(chosen_upgrade)
